package com.servlet.project.controller;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializer;
import com.servlet.project.entity.Administrator;
import com.servlet.project.entity.Member;
import com.servlet.project.entity.Recommendation;
import com.servlet.project.service.MemberService;
import com.servlet.project.util.Result;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;

@WebServlet(name = "MemberServlet",urlPatterns = "/MemberServlet")
public class MemberServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String method=request.getParameter("method");
        request.setCharacterEncoding("utf-8");
        MemberService service=new MemberService();
        if(method.equals("get")){//获取当前账号
            response.setContentType("text/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            if(request.getSession().getAttribute("member")==null){
                writer.write(new Gson().toJson(Result.reError("请先登录")));
            }else{
                Member member=(Member)request.getSession().getAttribute("member");
                // 创建一个日期格式化对象，设置为中文
                SimpleDateFormat chineseDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINESE);
                // 创建一个Gson对象，设置日期格式化
                Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting()
                        .registerTypeAdapter(Date.class, (JsonSerializer<Date>) (src, typeOfSrc, context) -> new JsonPrimitive(chineseDateFormat.format(src)))
                        .create();
                writer.write(gson.toJson(Result.reOk("",member)));
            }
        }else if(method.equals("getId")){//获取当前信息
            response.setContentType("text/json;charset=utf-8");
            String memberid=request.getParameter("memberid");
            Member member=service.getId(memberid);
            //将当前用户信息转化为json传回给前端（用的JSON的转化方法）
            PrintWriter writer = response.getWriter();
            // 创建一个日期格式化对象，设置为中文
            SimpleDateFormat chineseDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINESE);
            // 创建一个Gson对象，设置日期格式化
            Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting()
                    .registerTypeAdapter(Date.class, (JsonSerializer<Date>) (src, typeOfSrc, context) -> new JsonPrimitive(chineseDateFormat.format(src)))
                    .create();
            writer.write(gson.toJson(Result.reOk("ok",member)));
        }else if(method.equals("list")){//列表
            response.setContentType("text/json;charset=utf-8");
            String membername=request.getParameter("membername");
            String pageStr=request.getParameter("page");
            String rowsStr=request.getParameter("rows");
            int page=1;
            int rows=10;
            if(pageStr!=null&&!pageStr.equals("")){
                page=Integer.parseInt(pageStr);
            }
            if(rowsStr!=null&&!rowsStr.equals("")){
                rows=Integer.parseInt(rowsStr);
            }
            Member obj=new Member();
            obj.setMembername(membername);
            //获取当前总数
            int dataCount=service.getListCount(obj);
            //获取分页后的列表数据
            List<Member> memberList=service.getListAll((page-1)*rows,rows,obj);
            PrintWriter writer = response.getWriter();
            Map<String,Object> objectMap=new HashMap<>();
            objectMap.put("count",dataCount);
            objectMap.put("data",memberList);
            // 创建一个日期格式化对象，设置为中文
            SimpleDateFormat chineseDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINESE);
            // 创建一个Gson对象，设置日期格式化
            Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting()
                    .registerTypeAdapter(Date.class, (JsonSerializer<Date>) (src, typeOfSrc, context) -> new JsonPrimitive(chineseDateFormat.format(src)))
                    .create();
            writer.write(gson.toJson(Result.reOk("ok",objectMap)));
        }else if(method.equals("up")){//修改
            response.setContentType("text/json;charset=utf-8");
            String memberName=request.getParameter("membername");
            String memberPassword=request.getParameter("memberpassword");
            String memberBirthdate=request.getParameter("memberbirthdate");
            String memberSex=request.getParameter("membersex");
            String memberEmail=request.getParameter("memberemail");
            String memberId=request.getParameter("memberid");
            List<Object> objects=new ArrayList<>();
            objects.add(memberName);
            objects.add(memberPassword);
            objects.add(memberBirthdate);
            objects.add(memberSex);
            objects.add(memberEmail);
            objects.add(memberId);
            int count=service.up(objects);
            //将当前用户信息转化为json传回给前端（用的JSON的转化方法）
            PrintWriter writer = response.getWriter();
            if(count==1){//注册成功
                writer.write(new Gson().toJson(Result.reOk("修改成功")));
            }else{//注册失败
                writer.write(new Gson().toJson(Result.reError("修改失败")));
            }
        }else if(method.equals("get")){//获取当前信息
            response.setContentType("text/json;charset=utf-8");
            String memberId=request.getParameter("memberid");
            Member member=service.getId(memberId);
            //将当前用户信息转化为json传回给前端（用的JSON的转化方法）
            PrintWriter writer = response.getWriter();
            // 创建一个日期格式化对象，设置为中文
            SimpleDateFormat chineseDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINESE);
            // 创建一个Gson对象，设置日期格式化
            Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting()
                    .registerTypeAdapter(Date.class, (JsonSerializer<Date>) (src, typeOfSrc, context) -> new JsonPrimitive(chineseDateFormat.format(src)))
                    .create();
            writer.write(gson.toJson(Result.reOk("ok",member)));
        }else if(method.equals("del")){//删除
            response.setContentType("text/json;charset=utf-8");
            String memberId=request.getParameter("memberid");
            List<Object> objects=new ArrayList<>();
            objects.add(memberId);
            int count=service.del(objects);
            //将当前用户信息转化为json传回给前端（用的JSON的转化方法）
            PrintWriter writer = response.getWriter();
            if(count==1){//删除成功
                writer.write(new Gson().toJson(Result.reOk("删除成功")));
            }else{//删除失败
                writer.write(new Gson().toJson(Result.reError("删除失败")));
            }
        }



    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          doPost(request,response);
    }

}
